<script setup lang="ts">
import Run from '@/components/icons/code/Run.vue';
import Save from '@/components/icons/code/Save.vue';
import Set from '@/components/icons/code/Set.vue';
import Back from '@/components/icons/code/Back.vue';
import Ai from '@/components/icons/code/Ai.vue';
import { router } from '@/router';
import { onUnmounted, ref, Ref, watch } from 'vue';
import { CodeContent } from '@/api/code/type';
import { saveCodeContent } from '@/api/code';
import { getSolveSuggestions } from '@/api/code/codeCompletion';
import MarkdownRenderer from './MarkdownRenderer.vue'

const name = defineModel("name")
const codeContent = defineModel("codeContent") as Ref<CodeContent>;
const codeId = defineModel("codeId") as Ref<string>;
const termContent = defineModel("termContent") as Ref<string>
const timeout = ref({} as NodeJS.Timeout);
const loading = ref(false);
const emit = defineEmits(["run"]);
const solveNotice = ref("您好！\n欢迎使用SQL纠错助手，请输入代码或运行代码~🫡");
const showPopup = ref(false);
let showText = ref('AI思考中...');
const back = () => {
    router.back();
}
const run = () => {
    emit("run");
}
const save = () => {
    codeContent.value.codeId = codeId.value;
    saveCodeContent(codeContent.value);
}

function getErrorLogText(text: string): string {
    // 正则表达式匹配以 ERROR 开头的段落
    const errorRegex = /^ERROR[\s\S]*?(?=\n{2,}|$)/gm;
    const errorParagraphs = text.match(errorRegex) || [];

    // 将段落用换行符拼接
    return errorParagraphs.join('\n');
}

const onClickCloseIcon = () => {
    showText.value = '';
}

const toSolve = async () => {
    console.log("termContent: ", termContent.value);
    showPopup.value = true;
    if (termContent.value.length !== 0 || codeContent.value.content.length !== 0) {
        const errorLog = getErrorLogText(termContent.value);
        const codeText = codeContent.value.content;
        loading.value = true;
        console.log("errorLog: ", errorLog);
        try {
            let data = await getSolveSuggestions(codeText, errorLog);
            console.log("response: ", data)
            if (data.length === 0) {
                throw new Error(`解析错误！未获取到数据`);
            }
            showText.value = data.substring(3, data.length - 3);
        } catch (e) {
            showText.value = "SQL纠错助手暂时出现错误💀<br>请稍后重试🤕";
        } finally {
            loading.value = false;
        }
    } else {
        showText.value = '';
        showText.value = solveNotice.value;
    }
}

watch(() => codeContent.value.content, () => {
    if (timeout.value) clearTimeout(timeout.value);
    timeout.value = setTimeout(() => {
        save();
    }, 5000);
})

onUnmounted(() => {
    clearTimeout(timeout.value);
})
</script>

<template>
    <div class="content">
        <Back @click="back" style="margin-right: 3%;"></Back>
        <p>{{ name }}</p>
        <div class="right">
            <Run class="run" @click="run"></Run>
            <Save style="margin-left: 10px;" @click="save"></Save>
            <Set style="margin-left: 10px;"></Set>
            <van-loading v-if="loading" type="spinner" size="23px" style="margin-left: 10px;padding-top: 3px;"
                color="#7F98AB" />
            <Ai v-else="loading" style="margin-left: 10px;padding-top: 1px;" @click="toSolve"></Ai>
        </div>
        <van-popup v-model:show="showPopup" closeable round @click-close-icon="onClickCloseIcon" style=""
            class="popupView">
            <h3 style="width: 100%;text-align: center;">SQL纠错助手</h3>
            <MarkdownRenderer style="width: 100%;" :content="showText" />
        </van-popup>
    </div>
</template>

<style lang="scss" scoped>
p {
    width: 50%;
    color: white;
}

.content {
    display: flex;
    align-items: center;
    width: 94%;
    padding-left: 3%;
    padding-right: 3%;

    .right {
        width: calc(50%);
        display: flex;
        justify-content: right;
    }
}

.popupView {
    width: 80%;
    height: 50%;
    padding: 15px;
    overflow-x: auto;
    /* Firefox 64+ */
    scrollbar-width: none;
    /* IE/Edge */
    -ms-overflow-style: none;
}

/* WebKit 内核浏览器 */
.popupView::-webkit-scrollbar {
    display: none;
    /* Chrome/Safari/Opera */
}
</style>